package com.tabbinder.server;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Link;

/** Link record, part of a Binder */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class LinkRecord {
	public static final String URL_KEY = "url";
	public static final String TITLE_KEY = "title";
	@NotPersistent
	private static Logger log = Logger.getLogger(Binder.class.getName());

	/** unique id for the record - we don't need it, but the data store might */
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key id;

	@Persistent
	private Link link;
	@Persistent
	private String title = null;

	public LinkRecord(Link link) {
		this.link = link;
	}

	public LinkRecord(JSONObject item) throws JSONException {
		this.link = new Link(item.getString(URL_KEY));
		try {
			this.title = item.getString(TITLE_KEY);
		} catch (JSONException ex) {
			this.title = null;
		}
	}

	@Override
	public String toString() {
		return link + (title == null ? "" : (" \"" + title + "\""));
	}

	public Link getLink() {
		return link;
	}

	public void setLink(Link link) {
		this.link = link;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public JSONObject toJson() {
		JSONObject res = new JSONObject();
		try {
			res.put(URL_KEY, link.toString());
			res.put(TITLE_KEY, title);
		} catch (JSONException e) {
			log.log(Level.SEVERE, "Cannot create JSON: ", e);
			return null;
		}
		return res;
	}

	public Key getId() {
		return id;
	}
}
